package com.company.linkedList;

public class RotationList {

    public ListNode rotateRight(ListNode head, int k) {
        if (head==null) {
            return null;
        }
        return insertTail(head, k,false);
    }

    public ListNode rotateLeft(ListNode head,int k){
        if (head == null) {
            return null;
        }
        return insertTail(head, k,true);
    }

    private ListNode insertTail(ListNode head,int k,boolean left){
        ListNode newHead=head;
        ListNode tailNode = null;
        ListNode node = head;

        int lengh=1;
        while (node.next!=null){
            node = node.next;
            lengh++;
        }
        k = k%lengh;

        if (!left) {
            k=lengh-k;
        }
        tailNode = node;

        node = head;
        for (int i = 0; i < k; i++) {
            tailNode.next = node;
            newHead = node.next;
            node.next = null;
            tailNode = node;
            node = newHead;
        }
        return newHead;
    }
}
